const fs = require("fs-extra")
const path = require("path")

module.exports = class Window {

    constructor(browser, context, name) {
        this.browser = browser
        this.context = context
        this.name = name
        this.robot = null
    }

    // 载入机器人对象
    loadRobot(robot) {
        this.robot = robot
        this.robot.context = this.context
        this.robot.createRequestInfo = this.createRequestInfo
        this.robot.saveRequestInfo = this.saveRequestInfo
        return this.robot
    }

    // 解析请求
    async createRequestInfo(request) {
        const res = {}

        res.resourceType = request.resourceType()
        res.url = request.url()
        res.URL = new URL(res.url)
        res.method = request.method()
        res.headers = request.headers()
        res.postData = request.postData()
        res.fetchPostData = await request.fetchPostData()

        const response = request.response()

        if (response) {

            res.response = {}
            res.response.status = response.status()
            res.response.statusText = response.statusText()
            res.response.headers = response.headers()

            try {
                res.response.content = await response.content()
            } catch (e) { }

            try {
                res.response.buffer = await response.buffer()
            } catch (e) { }

            try {
                res.response.text = await response.text()
            } catch (e) { }

            try {
                res.response.json = await response.json()
            } catch (e) { }

            res.response.fromCache = response.fromCache()
            res.response.remoteAddress = response.remoteAddress()

        }

        return res

    }

    // 保存请求
    async saveRequestInfo(requestinfo, _options = {}) {

        // 参数
        const options = {
            saveDir: __dirname,
            resourceType: null,
            onlyJson: false,
            ..._options
        }

        // 跳过 不需要的资源
        if (options.resourceType && !options.resourceType.includes(requestinfo.resourceType)) return

        // 仅保存json
        if (options.onlyJson) {
            delete requestinfo.response.content
            delete requestinfo.response.buffer
            delete requestinfo.response.text
        }

        // 确保保存目录存在
        fs.ensureDirSync(options.saveDir)

        // 基础文件名
        let baseSaveName = requestinfo.url.replace(/[^a-zA-Z0-9]/g, "_")

        // 同名文件 加序号
        let i = 0
        while (fs.existsSync(path.join(options.saveDir, baseSaveName + `-${i}` + ".json"))) i++
        baseSaveName += `-${i}`

        // 取后200个字符
        baseSaveName = baseSaveName.slice(-200)

        // 保存文件名
        const savePath = path.join(options.saveDir, baseSaveName + ".json")

        // 保存数据
        fs.writeJSONSync(savePath, requestinfo, { spaces: 4 })


    }

    action(actionName, args = []) {
        return this.robot[actionName](...args)
    }


    async close() {
        this.browser.closeWindow(this.name)
    }

}